import { useMemberStore } from "@/store/member";
const baseURL = "https://pcapi-xiaotuxian-front-devtest.itheima.net";
uni.addInterceptor("request", {
  invoke(args) {
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    // request 触发前拼接 url
    if (!(args.url as string).startsWith("https://")) {
      args.url = baseURL + args.url;
    }
    const store = useMemberStore();
    // console.log("[ store.safeArea ] >", store.safeArea);
    // 小程序端调用，请求头中header中必须添加：source-client：miniapp
    args.header = {
      ...args.header, // 保留原本的 header
      'source-client': 'miniapp', // 添加小程序端调用标识
    }
    if (store.profile.token) {
      // console.log("[ store.token ] >", store.token);
      const herder = { Authorization: "" };
      herder.Authorization = `Bearer ${store.profile.token}`;
      args.header = Object.assign(herder, args.header);
    }
    // console.log("[ args ] >", args);
  },
  // success(args) {
  //   // 请求成功后，修改code值为1
  //   args.data.code = 1;
  // },
  // fail(err) {
  //   console.log("interceptor-fail", err);
  // },
  // complete(res) {
  //   console.log("interceptor-complete", res);
  // },
});

interface defaultResult {
  msg: string;
  result: any;
  statusCode: number;
}
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<T>((resolve, reject) => {
    uni.request({
      ...options,
      success: (success) => {
        if (success.statusCode >= 200 && success.statusCode <= 300) {
          resolve((success.data as defaultResult).result);
        } else {
          if (success.statusCode === 401) {
            const pageStack = getCurrentPages()
            // 获取最后一个一个页面的页面实例
            const prevPage = pageStack[pageStack.length - 1]
            console.log('401跳转页面了');
            uni.redirectTo({
              url: '/pages/login/index?redirectURL=' + prevPage.route
            })
          }
          uni.showToast({ title: (success.data as any).message, icon: 'none' })
          reject(success);
        }
        uni.hideLoading();
      },
      fail: (err) => {
        uni.showToast({ title: err.errMsg, icon: 'none' })
        reject(err);
        uni.hideLoading();
      },
    });
  });
};
